#include "DualRecvRelayHandlerBase.h"

using namespace log4cplus;

Logger DualRecvRelayHandlerBase::log=GetLogger(LOG4CPLUS_TEXT("DualRecvRelayHandlerBase"));

ITransHandler::ExecuteResultCode DualRecvRelayHandlerBase::Execute(ClientContext &client,OVERLAPPED *ovl)
{
	unsigned int clienSequenceNo=client.SequenceNo();
	SOCKET recvSock;
	SOCKET sendSock;
	WSABUF *buf;
	OVERLAPPED *ovlData;
	WSABUF *weakRefBuf;
	GetRecvSendInfo(client,&recvSock,&sendSock,&buf,&ovlData,&weakRefBuf);

	DWORD recvCount=-1;
	DWORD flags;
	BOOL result=::WSAGetOverlappedResult(recvSock,ovlData,&recvCount,true,&flags);
	int errCode=::WSAGetLastError();
	if(result)
	{
		if(recvCount==0)
		{
			LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Dual receive 0 byte data,exit."),clienSequenceNo);
			return ITransHandler::ExecuteFinished;
		}
		else
		{
			LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Dual receive %d bytes data,begin to translate."),clienSequenceNo,recvCount);
			SetNextHandler(client);
			weakRefBuf->buf=buf->buf;
			weakRefBuf->len=recvCount;
			int sendResult=::WSASend(sendSock,weakRefBuf,1,NULL,0,ovlData,NULL);
			errCode=::WSAGetLastError();
			if(sendResult!=0&&errCode!=WSA_IO_PENDING)
			{
				LOG4CPLUS_ERROR_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin translate data failed,error code:%d."),clienSequenceNo,errCode);
				return ITransHandler::ExecuteFatalError;
			}
			LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin to translate data successed."),clienSequenceNo);
		}
	}
	else
	{
		LOG4CPLUS_ERROR_FMT(log,LOG4CPLUS_TEXT("[Client%d]Dual receive data failed,error code:%d."),clienSequenceNo,errCode);
		return ITransHandler::ExecuteFatalError;
	}
	return ITransHandler::ExecuteOK;
}